﻿using System;
using System.Reflection;

namespace Ops.Mpc.ValidationServices.Attributes
{
    [AttributeUsage(AttributeTargets.Property)]
    public class RequireMustMatchAttribute : ValidationAttribute
    {
        #region Fields
        public string PropertyName
        {
            get;
            set;
        }
        #endregion

        #region Constructors
        public RequireMustMatchAttribute(string propertyName)
        {
            this.PropertyName = propertyName;
        }

        public override bool Validate(object container, object data, string[] propertyNames)
        {
            PropertyInfo propertyInfo = container.GetType().GetProperty(PropertyName);
            object compareData = propertyInfo.GetValue(container, new object[] { });

            if (data == null && compareData == null)
                return true;
            if (data == null)
                return false;

            return data.Equals(compareData);
        }

        public override string FormatMessage(string messageFormat, object container, object data, string name)
        {
            return string.Format(messageFormat, name, this.PropertyName.ToLower());
        }
        #endregion
    }
}
